import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {AdminMoudel} from '../admin-moudel';
import {RoleService} from '../../role/role.service';
import {AdminService} from '../admin.service';
import {NzMessageService} from 'ng-zorro-antd';
import {ActivatedRoute} from '@angular/router';
import {Location} from '@angular/common';

@Component({
    selector: 'app-show',
    templateUrl: './show.component.html',
})
export class ShowComponent implements OnInit {
    adminForm: FormGroup;
    idOfRole: any[] = [];
    isVisibile = true;

    adminMoudel: AdminMoudel = new AdminMoudel();

    constructor(private fb: FormBuilder,
                private location: Location,
                private activityRoute: ActivatedRoute,
                private msg: NzMessageService,
                private roleService: RoleService,
                private adminService: AdminService,) {
        this.adminForm = this.fb.group({
            id: [0],
            username: ['', [Validators.required, Validators.maxLength(10), Validators.minLength(5)]],
            password: ['', [Validators.required, Validators.pattern(/^[a-zA-Z0-9]*$/), Validators.maxLength(16), Validators.minLength(6)]],
            roleId: ['', Validators.required],
        });
    }

    ngOnInit() {
        const id = this.activityRoute.snapshot.paramMap.get('id');
        if (id) {
            this.isVisibile = false;
            this.adminService.showAdmin(id).subscribe(res => {
                this.adminMoudel.id = res['id'];
                this.adminMoudel.username = res['name'];
                this.adminMoudel.password = '123456';
                this.adminMoudel.roleId = res['roles'];
                this.adminForm.patchValue({
                    id: this.adminMoudel['id'],
                    roleId: this.adminMoudel['roleId'].length !== 0 ? '1' : '',
                    password: this.adminMoudel.password,   // 用于表单判断，不上传
                    username: this.adminMoudel.username // 用于表单判断，不上传
                });
                this.roleService.getRoleList().subscribe(r => {
                    const ret = [];
                    for (let i = 0; i < r['list'].length; i++) {
                        ret.push({
                            key: r['list'][i]['id'].toString(),
                            title: r['list'][i]['name'],
                        });
                    }
                    this.idOfRole = ret;
                    for (let i = 0; i < this.adminMoudel['roleId'].length; i++) {
                        for (let j = 0; j < this.idOfRole.length; j++) {
                            if (this.adminMoudel['roleId'][i] === this.idOfRole[j]['key']) {
                                this.idOfRole[j].direction = 'right';
                            }
                        }
                    }
                });
            });
        } else {
            this.getRoleList();
            this.isVisibile = true;
        }
    }

    setStyle() {
        const styles = {
            'display': this.isVisibile ? 'block' : 'none',
        };
        return styles;
    }

    /**
     * 获取角色列表
     */
    getRoleList() {
        this.roleService.getRoleList().subscribe(res => {
            const ret = [];
            for (let i = 0; i < res['list'].length; i++) {
                ret.push({
                    key: res['list'][i]['id'].toString(),
                    title: res['list'][i]['name'],
                });
            }
            this.idOfRole = ret;
        });
    }

    /**
     * 选中回调
     * @param $event
     */
    select($event) {
        console.log($event);
    }

    /**
     * 穿梭回调
     * @param $event
     */
    change($event) {
        let ret = this.adminMoudel['roleId'];

        for (let i = 0; i < $event['list'].length; i++) {
            const temp = $event['list'][i]['key'].toString();
            if ($event['to'] === 'right') {
                ret.push(temp);
            } else {
                const index = ret.indexOf(temp);
                ret = [...ret.slice(0, index), ...ret.slice(index + 1, ret.length)];
            }
        }
        this.adminMoudel['roleId'] = ret;
        if (ret && ret.length > 0) {
            this.adminForm.patchValue({roleId: ret});
        } else {
            this.adminForm.patchValue({roleId: ''});
        }
    }

    /**
     * 添加/修改管理员
     */
    submit() {
        const res = this.adminForm.value;
        this.adminMoudel['id'] = res['id'];
        if (res['id'] === 0) {
            this.adminMoudel['username'] = res['username'];
            this.adminMoudel['password'] = res['password'];
        }

        console.log(JSON.stringify(this.adminMoudel));

        this.adminService.addAdmin(this.adminMoudel).subscribe(__ => {
            this.msg.success('提交成功');
            this.location.back();
        }, e => {
            console.error(e);
        });
    }

    /**
     * 返回
     */
    back() {
        this.location.back();
    }
}
